package com.app.db.notify;

import android.content.Context;
import android.text.TextUtils;

import com.app.db.BaseDBManager;
import com.app.db.dao.DaoSession;
import com.app.db.dao.NotifyBeanDao;
import com.app.ui.notification.InformManager;
import com.app.utiles.other.APKInfo;
import com.app.utiles.other.DLog;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * 通知
 * Created by Administrator on 2016/10/21.
 */
public class NotifyDBManager extends BaseDBManager {

    private static NotifyBeanDao dao;

    private static void initInstance() {
        if (dao != null) {
            return;
        }
        DaoSession daoSession = getDM().newSession();
        dao = daoSession.getNotifyBeanDao();
    }

    //保存 数据
    public static void insertInTx(NotifyBean notifyBean) {
        initInstance();
        dao.insert(notifyBean);
    }

    //获取一个通知
    public static NotifyBean getNotify(String consultId) {
        if (TextUtils.isEmpty(consultId)) {
            return null;
        }
        initInstance();
        QueryBuilder<NotifyBean> qb = dao.queryBuilder();
        qb.where(NotifyBeanDao.Properties.ConsultId.eq(consultId));
        List<NotifyBean> list = qb.list();
        NotifyBean notifyBean = null;
        if (list != null && list.size() > 0) {
            notifyBean = list.get(0);
        }
        return notifyBean;
    }

    //获取自大的通知id
    public static int getMaxNotifyId() {
        int notifyId = 0;
        initInstance();
        List<NotifyBean> list = dao.queryBuilder().orderDesc(NotifyBeanDao.Properties.NotifyId).list();
        if (list != null && list.size() > 0) {
            notifyId = list.get(0).getNotifyId();
        }
        DLog.e("NotifyDBManager", "最大的通知id：" + notifyId);
        return notifyId;
    }

    //删除一个通知
    public static void deleteNotify(Context context, String consultId) {
        if (TextUtils.isEmpty(consultId)) {
            return;
        }
        boolean isBack = APKInfo.getInstance().isBackground();
        if (isBack) {
            return;
        }
        initInstance();
        NotifyBean notifyBean = dao.queryBuilder().where(
                NotifyBeanDao.Properties.ConsultId.eq(consultId)).build().unique();
        if (notifyBean == null) {
            return;
        }
        dao.delete(notifyBean);
        InformManager.getInstance(context).clearNotifyId(notifyBean.notifyId);
    }

    //删除表数据
    public static void deleteAll() {
        initInstance();
        dao.deleteAll();
    }
}
